package mn.idax.exchange.otc.util;

import com.alibaba.fastjson.JSON;
import mn.idax.exchange.common.SpringUtils;
import mn.idax.exchange.otc.config.RedisSubListenerConfig;
import mn.idax.exchange.otc.dto.ChatProtocol;
import mn.idax.exchange.otc.dto.ChatRoomAttributes;
import mn.idax.exchange.otc.entity.ChatLog;
import mn.idax.exchange.otc.entity.UserInfo;
import mn.idax.exchange.otc.enums.MessageNotifyTemplateEnum;
import mn.idax.exchange.otc.service.ChatLogService;
import mn.idax.exchange.otc.service.ChatRedisService;
import mn.idax.exchange.otc.service.ChatRoomService;
import org.apache.commons.lang3.StringUtils;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.Broadcaster;
import org.atmosphere.cpr.BroadcasterFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.text.MessageFormat;
import java.util.Collection;

/**
 * @Auther: dison
 * @Date: 2018/9/11 16:40
 * @Description:
 */
public class MessageNotifyUtils {


    private static final Logger logger = LoggerFactory.getLogger(MessageNotifyUtils.class);
//    public final static String STAFF_ORDER = "staff_order";
//    public final static String STAFF_USER = "staff";
    //订单状态变更消息订阅topic
    public static final String OTC_ORDER_STATE_CHANGE_EVENT = "OTC_ORDER_STATE_CHANGE_EVENT";

    private final static String CHAT_ROOM_ATTRIBUTES = "chatRoomAttributes";

    /**
     *
     * 功能描述:
     *      客服进入通知
     * @param:
     * @return:
     * @auther: dison
     * @date: 2018/9/11 17:07
     */
    public static void joinStaffNotify(AtmosphereResource resource,ChatRoomAttributes chatRoomAttributes){
        if (!resource.getBroadcaster().isDestroyed()){
            pushStaffNotify(resource , MessageNotifyTemplateEnum.Type.join,chatRoomAttributes);
        }
    }

    public static void pushTemporaryNotify(AtmosphereResource resource,Broadcaster broadcaster,MessageNotifyTemplateEnum.Type type){
        logger.info("----pushTemporaryNotify start ...----");
        if (!resource.getBroadcaster().isDestroyed()){
//            String orderId = resource.getRequest().getSession(false).getAttribute(STAFF_ORDER).toString();
            String orderId = ((ChatRoomAttributes)resource.getRequest().getSession(false).getAttribute("chatRoomAttributes")).getStaff_order();
            logger.info("----pushTemporaryNotify orderId is {} ----",orderId);
            String userName = "IDAX ";
            String notifyContent = null;
            if (type == MessageNotifyTemplateEnum.Type.join){
                notifyContent = MessageNotifyTemplateEnum.staff_join.getContent();
            }else if (type == MessageNotifyTemplateEnum.Type.quit){
                notifyContent = MessageNotifyTemplateEnum.staff_quit.getContent();
            }

            ChatProtocol chatProtocol = ChatProtocol.defalutSystemMessage(notifyContent);
            chatProtocol.setUserName(userName);
            chatProtocol.setSenderId(0);
            chatProtocol.setOrderId(orderId);
            chatProtocol.setSaved(true);

            SpringUtils.getBean(ChatRedisService.class).pushMessageToRedis(RedisSubListenerConfig.OTC_ORDER_STATE_CHANGE_EVENT, JSON.toJSONString(chatProtocol));
//            if (broadcaster == null) {
//                logger.warn("----receive message from redis, but broadcaster not found----");
//                return;
//            }
//
//            /**check current connect**/
//            Collection<AtmosphereResource> resourceCollection = broadcaster.getAtmosphereResources();
//            if (resourceCollection.isEmpty()) {
//                logger.warn("----receive message from redis, but broadcaster not found----");
//            } else {
//                /**broadcast message **/
//                broadcaster.broadcast(chatProtocol);
//            }
        }
    }


    /**
     *
     * 功能描述:
     *      客服离开通知
     * @param:
     * @return:
     * @auther: dison
     * @date: 2018/9/11 17:07
     */
    public static void quitStaffNotify(AtmosphereResource resource,Broadcaster broadcaster){
        if (!resource.getBroadcaster().isDestroyed()){
//            pushStaffNotify(resource , MessageNotifyTemplateEnum.Type.quit);
//            String orderId = resource.getRequest().getSession(false).getAttribute(STAFF_ORDER).toString();
            String orderId = ((ChatRoomAttributes)resource.getRequest().getSession(false).getAttribute("chatRoomAttributes")).getStaff_order();

            String userName = "IDAX ";
            String notifyContent = MessageNotifyTemplateEnum.staff_quit.getContent();

            ChatProtocol chatProtocol = ChatProtocol.defalutSystemMessage(notifyContent);
            chatProtocol.setUserName(userName);
            chatProtocol.setSenderId(0);
            chatProtocol.setOrderId(orderId);

//            Broadcaster broadcaster = ChatRoomService.broadcasterFactory.lookup(chatProtocol.getOrderId());
//            if (broadcaster == null) {
//                logger.warn("----receive message from redis, but broadcaster not found----");
//                return;
//            }

            /**check current connect**/
            Collection<AtmosphereResource> resourceCollection = broadcaster.getAtmosphereResources();
            if (resourceCollection.isEmpty()) {
                logger.warn("----receive message from redis, but broadcaster not found----");
            } else {
                /**broadcast message **/
                broadcaster.broadcast(chatProtocol);
            }

        }
    }

    /**
     *
     * 功能描述:
     *      获取用户昵称
     * @param:
     * @return:
     * @auther: dison
     * @date: 2018/9/11 17:07
     */
    public static String getNotifyUserNameByUserInfo(UserInfo userInfo){
        if (StringUtils.isNotEmpty(userInfo.getUserName())){
            return userInfo.getUserName();
        }
        return userInfo.getEmail();
    }

    /**
     *
     * 功能描述:
     *      获取客服通知内容
     * @param:
     * @return:
     * @auther: dison
     * @date: 2018/9/11 17:07
     */
    public static void pushStaffNotify(AtmosphereResource resource, MessageNotifyTemplateEnum.Type type,ChatRoomAttributes chatRoomAttributes){
        String orderId = chatRoomAttributes.getStaff_order();
        /*String userName = getNotifyUserNameByUserInfo(userInfo);*/
        String userName = "IDAX ";
        String notifyContent = null;
        if (type == MessageNotifyTemplateEnum.Type.join){
            notifyContent = MessageNotifyTemplateEnum.staff_join.getContent();
        }else if (type == MessageNotifyTemplateEnum.Type.quit){
            notifyContent = MessageNotifyTemplateEnum.staff_quit.getContent();
        }

        ChatProtocol chatProtocol = ChatProtocol.defalutSystemMessage(notifyContent);
        chatProtocol.setUserName(userName);
        chatProtocol.setSenderId(0);
        chatProtocol.setOrderId(orderId);
        chatProtocol.setBuyerReadFlag(chatRoomAttributes.getUser().equals(chatRoomAttributes.getBuyerId()) ? 1 : 0);
        chatProtocol.setSellerReadFlag(chatRoomAttributes.getUser().equals(chatRoomAttributes.getSellId()) ? 1 : 0);
        chatProtocol.setBuyerId(chatRoomAttributes.getBuyerId());
        chatProtocol.setBuyerReadFlag(chatRoomAttributes.getSellId());
        chatProtocol.setOrderNum(chatRoomAttributes.getOrderNum());

        ChatLog chatLog = saveChatLogToMongo(chatProtocol);
        if (chatLog == null) {
            logger.warn("----save chat log to mongo failure:{}----", JSON.toJSONString(chatProtocol));
            return;
        }
        /**3:send message to related client**/
        chatProtocol.setSaved(true);//添加一个特殊标识

        resource.getRequest().getSession().setAttribute(CHAT_ROOM_ATTRIBUTES, chatRoomAttributes);
        StringRedisTemplate stringRedisTemplate = SpringUtils.getBean(StringRedisTemplate.class);
        stringRedisTemplate.convertAndSend(OTC_ORDER_STATE_CHANGE_EVENT, JSON.toJSONString(chatProtocol));

//        return JSON.toJSONString(chatProtocol);
    }


    /**
     * saveChatLogToMongo
     *
     * @param chatProtocol
     * @return
     */
    private static ChatLog saveChatLogToMongo(ChatProtocol chatProtocol) {
        try {
            if (chatProtocol != null) {
                ChatLog chatLog = new ChatLog();
                BeanUtils.copyProperties(chatProtocol, chatLog);
                logger.info("::::SaveChatLog::ChatRoom", JSON.toJSONString(chatLog));
                return SpringUtils.getBean(ChatLogService.class).insert(chatLog);
            }
        } catch (Exception e) {
            logger.error("----save chatLog to mongo error----", e);
        }
        return null;
    }
}
